package com.servlet.utils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Title: BaseServlet
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2023/12/22 11:19
 * http://localhost:8080/web/edit
 * http://localhost:8080/web/add
 * http://localhost:8080/web/delete
 * http://localhost:8080/web/query
 *
 * http://localhost:8080/web/user?method=add
 * http://localhost:8080/web/user?method=edit
 * http://localhost:8080/web/user?method=ddlete
 * http://localhost:8080/web/user?method=query
 */
public class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("utf-8");
           // 调用  UserServlet 中的  add /edit/delete/query方法
           // 1 获取指定的方法名字
          String method = req.getParameter("method");
          // 2. 找到子类的 class
        try {
            resp.setHeader("Content-Type","text/plain;charset=utf-8");
            Method m = this.getClass().getDeclaredMethod(method,HttpServletRequest.class,HttpServletResponse.class);
            m.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
